<?php

namespace Morrow;

class PageController extends DefaultController {
	public function run() {
		$this->form->loadDef(
			array('myform' => array(

		            "email" => array(
		            	"type" => "text",
		            	"required" => true,
		            	"label" => "email :",
		            	"checktype" => "Email",
	            	),

	            	"password" => array(
		            	"required" => true,
		            	"type" => "text",
		            	"displaytype" => "password",
		            	"checktype" => "password",
		            	"compare" => "password2",
		            	"label" => "password :",


	            	),

	            	"password2" => array(
	            		"required" => true,
	            		"type" => "text",
	            		"displaytype" => "password",
	            	)
            	)
            )
        );

		if($this->session->get("uid")){
			$this -> url -> redirect('home');
		}
		
		$this->form->setInput($this->input->get());


		if($this -> form -> isSubmitted('myform')) {
    			$valid = $this -> form -> validate('myform');

            	$this->view->setContent($this->form->getErrors('myform'), "error");



    				if ($valid) {
        		        $formdata = $this -> form -> getValues('myform');
        				
                        $this->load('Db', $this->config->get('db'));


                        $sql = $this->db->result('
							SELECT uid
							FROM users
							WHERE email = ?'
							, $formdata['email']);

                        $check_email_already = $sql["NUM_ROWS"];

                        if($check_email_already == 1){
                        	$this->form->setError('myform','email',$this->language->_('邮件已经存在') );
                        }
                        else{
	                        $now = date("Y-m-d H:i:s",time());
	                        $register_time = array('register_time'=> $now);
	        				$data=array_merge($formdata, $register_time );

	        				$data['password'] = md5($data['password']);

							$this->db->insertSafe('users', $data, true);

							$this->session->set('messenger','register1');
		        			//var_dump($data);
		        			$this -> url -> redirect('home');


                        }
                        

                        

    				} 
    				else {
    				}
		}

	}
}
